import 'dart:async';
import 'dart:io';
import 'dart:convert' show json;
import 'package:flutter/material.dart';
import 'path_utils.dart';
import 'file_utils.dart';
import 'package:intl/intl.dart';
enum LogType {
   Push,//入栈
   Pop,//出栈
   Remove,//
   Replace,//
   StartUserGesture,//
   StopUserGesture,//
   NoSuchMethod,//
  //页面内监听
   resumed,//
   inactive,//
   paused,//
   suspending,//
}

class Log {
  //对应界面的操作方式，push，pop...
  final LogType what;
  //什么时间
  final DateTime when;
  //上一界面
  final String fWhere;
  //下一界面
  final String tWhere;
  //路由参数
  final String params;
  //用户id
  final String userId;
  //扩展数据
  final String ext;
  Log(
      {
      this.what,
      this.when,
      this.fWhere,
      this.tWhere,
      this.params,
      this.userId,
      this.ext
      }
      );
  String toJsonString() {
    var formatter = new DateFormat('yyyy-MM-dd HH:mm:ss');

    Map map = {};
    if(this.what!=null)  map["what"] = this.what.toString();
    if(this.when!=null)  map["when"] = this.when==null?"":formatter.format(this.when);
    if(this.fWhere!=null) map["fWhere"] = this.fWhere;
    if(this.tWhere!=null) map["tWhere"] = this.tWhere;
    if(this.params!=null) map["params"] = this.params;
    if(this.userId!=null) map["userId"] = this.userId;
    if(this.ext!=null) map["ext"] = this.ext;

    return json.encode(map);
  }

  @override
  String toString() {
    // TODO: implement toString
    return super.toString();
  }
}

class LogUtils {
  StreamController<Log> logController;
  Stream stream;
  StreamSink sink;
  StreamSubscription subscription;
  void log(Log log) {
    sink.add(log);
  }
  void logState(AppLifecycleState state,Type type) {
    LogType logType;
    if(state==AppLifecycleState.inactive){
      logType=LogType.inactive;
    }else if(state==AppLifecycleState.paused){
      logType=LogType.paused;
    }else if(state==AppLifecycleState.resumed){
      logType=LogType.resumed;
    }else if(state==AppLifecycleState.suspending){
      logType=LogType.suspending;
    }
    log(Log(
      what: logType,
      when: DateTime.now(),
      fWhere: type.toString(),
    ));
  }

  LogUtils._internal() {
    logController = StreamController<Log>.broadcast();
    stream = logController.stream;
    sink = logController.sink;
    subscription = stream.listen(onData);
  }
  factory LogUtils() => _getInstance();
  static LogUtils _instance;
  static LogUtils get instance => _getInstance();
  static LogUtils _getInstance() {
    if (_instance != null) return _instance;
    _instance = LogUtils._internal();
    return _instance;
  }

  void onData(value) {
    PathUtils.instance.then((directory) {
      String logPath = "${directory.tempDirectory.path}/log.txt";
      saveStringToFileSync(logPath, value.toJsonString()+"\n",fileMode: FileMode.write);
      String result=readStringFromFileSync(logPath);
      print("result:$result");
    });
  }
  void close(){
    logController.close();
    subscription.cancel();
  }
}
